package cn.cc.goods.init;

import cn.cc.common.contants.RedisKeyConstant;
import cn.cc.common.redis.RedisCommon;
import cn.cc.common.result.utils.RestResult;
import cn.cc.goods.service.GoodsSkuService;
import cn.cc.goods.service.GoodsSpuService;
import cn.cc.goods.service.GoodsTypeService;
import cn.cc.goods.service.domain.GetGoodsSkuDO;
import cn.cc.goods.service.domain.GetGoodsSpuDO;
import cn.cc.goods.service.domain.GetGoodsTypeDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: smail-mi-cloud
 * @description: 初始化加载商品信息
 * @author: Mr.WuChao
 * @create: 2021-07-17 09:38
 **/
@Component
public class InitGoods implements InitializingBean {
    //打印日志
    public static Logger logger = LoggerFactory.getLogger(InitGoods.class);
    //redis
    @Autowired
    private RedisCommon redisCommon;
    //商品sku
    @Autowired
    private GoodsSkuService skuService;
    //商品spu
    @Autowired
    private GoodsSpuService spuService;
    //商品type
    @Autowired
    private GoodsTypeService typeService;

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.debug("初始化数据开始");
        initSpu();
        initSku();
        initTpye();
        logger.debug("初始化数据结束");
    }

    public void initSku() {
        RestResult<List<GetGoodsSkuDO>> skuAll = skuService.getGoodSkuAll();
        // Map<String, GetGoodsSkuDO> map = skuAll.getData().stream().collect(Collectors.toMap(GetGoodsSkuDO::getGoodsId, GetGoodsSkuDO -> GetGoodsSkuDO));
        redisCommon.setList(RedisKeyConstant.SHOPPING_CAR_GOODS_CC_GOODS_SKU, skuAll.getData());
    }

    public void initSpu() {
        RestResult<List<GetGoodsSpuDO>> goodsSpu = spuService.getGoodsSpu();
        Map<String, GetGoodsSpuDO> map = goodsSpu.getData().stream().collect(Collectors.toMap(GetGoodsSpuDO::getGoodsId, GetGoodsSpuDO -> GetGoodsSpuDO));
        //redisCommon.addList(RedisKeyConstant.SHOPPING_CAR_GOODS_CC_GOODS_SPU,goodsSpu.getData());
        redisCommon.putHashAll(RedisKeyConstant.SHOPPING_CAR_GOODS_CC_GOODS_SPU, map);
    }

    public void initTpye() {
        RestResult<List<GetGoodsTypeDO>> typeAll = typeService.getGoodsTypeAll();
        Map<String, GetGoodsTypeDO> map = typeAll.getData().stream().collect(Collectors.toMap(GetGoodsTypeDO::getGoodsType, GetGoodsTypeDO -> GetGoodsTypeDO));
        redisCommon.putHashAll(RedisKeyConstant.SHOPPING_CAR_GOODS_CC_GOODS_TYPE, map);
    }
}
